package com.purchase.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.purchase.entity.OrderDetail;
import com.purchase.entity.Withdraw;
import com.purchase.entity.WxUserMember;
import com.purchase.mapper.*;
import com.purchase.util.LogInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.purchase.service.StatisticsService;
import com.purchase.util.DateUtil;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;

import lombok.extern.slf4j.Slf4j;

import static java.util.stream.Collectors.groupingBy;

import java.math.BigDecimal;

@Service
@Slf4j
public class StatisticsServiceImpl implements StatisticsService {
    @Resource
    OrderMapper orderMapper;
    @Resource
    StoreActivityMapper saMapper;
    @Resource
    WxUserMapper wuMapper;

    @Autowired
    private WxUserMemberMapper wxUserMemberMapper;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private WithdrawMapper withdrawMapper;

    @Override
    public ResponseForm getSalesAndPriceData(RequestForm param) {
        ResponseForm result = new ResponseForm();
        if (param.getData() != null) {
            /* 今日: 总价 单数 商品 */
            Map paramMap = (Map) param.getData();
            paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
            paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
            LinkedHashMap resultMap = new LinkedHashMap<>();
            try {
                Map orderStatistics = orderMapper.getOrderStatistics(paramMap);
                resultMap.put("orderStatistics", orderStatistics);
            } catch (Exception e) {
                result.setStatus(false);
                result.setMessage("参数错误");
                log.error("参数错误");
                e.printStackTrace();
            }
            /* 按活动:总价 单数 商品件数 */
            try {
                /* 获取有数据的活动列表 */
                List<Map> activities = saMapper.getActivities(paramMap);
                if (activities != null) {
                    for (Map activity : activities) {
                        activity.put("startTime", paramMap.get("startTime"));
                        activity.put("endTime", paramMap.get("endTime"));
                        Map orderStatistics = orderMapper.getOrderStatistics(activity);
                        activity.put("orderStatistics", orderStatistics);
                    }
                }
                resultMap.put("activitiesOrderStatistics", activities);
            } catch (Exception e) {
                result.setStatus(false);
                result.setMessage("参数错误");
                log.error("参数错误");
                e.printStackTrace();
            }
            result.setData(resultMap);
        }
        return result;
    }

    @Override
    public ResponseForm getActivityOrderData(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            LinkedList<OrderDetail> orderDetails = orderMapper.getActivityOrderData(paramMap);
            LinkedList<Object> activityList = this.getGroupList(orderDetails);
            result.setData(activityList);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("获取活动订单详情error", e);
        }
        return result;
    }

    /**
     * 按 活动和订单 分组
     *
     * @param orderDetails 活动订单详情列表
     * @return
     */
    private LinkedList<Object> getGroupList(List<OrderDetail> orderDetails) {
        // 按 活动ID 分组
        LinkedList<Object> activityList = new LinkedList<>();
        Map<Integer, List<OrderDetail>> collectByActivity = orderDetails.parallelStream()
                .collect(groupingBy(OrderDetail::getActivityId));

        // 遍历 collectByActivity，以取到 first 里的活动名称活动ID 和订单列表
        collectByActivity.forEach((k, v) -> {
            Map<String, Object> mapByActivity = new HashMap<>();
            String activityName = v.get(0).getActivityName();
            mapByActivity.put("activityId", k);
            mapByActivity.put("activityName", activityName);

            // 按 订单ID 分组
            List<Map<String, Object>> orderList = new ArrayList<>();
            Map<String, List<OrderDetail>> collectByOrder = v.parallelStream()
                    .collect(groupingBy(OrderDetail::getOrderId));

            // 遍历 collectByOrder，以取到 first 里的订单ID 和商品列表
            collectByOrder.forEach((k1, v1) -> {
                Map<String, Object> mapByOrder = new HashMap<>();
                mapByOrder.put("orderId", k1);
                mapByOrder.put("orderPrice", v1.get(0).getOrderPrice());
                mapByOrder.put("postage", v1.get(0).getPostage());
                mapByOrder.put("orderStatus", v1.get(0).getOrderStatus());
                mapByOrder.put("logisticStatus", v1.get(0).getLogisticStatus());
                mapByOrder.put("orderGoodsNum", v1.get(0).getOrderGoodsNum());
                mapByOrder.put("contacts", v1.get(0).getContacts());
                mapByOrder.put("phone", v1.get(0).getPhone());
                mapByOrder.put("address", v1.get(0).getAddress());
                mapByOrder.put("createTime", v1.get(0).getCreateTime());
                mapByOrder.put("orderList", v1);
                orderList.add(mapByOrder);
            });

            // 按时间倒序
            List<Map<String, Object>> sortedTimeList = orderList.parallelStream().sorted(Comparator
                    .comparingLong((Map<String, Object> c) -> ((Date) (c.get("createTime"))).getTime()).reversed())
                    .collect(Collectors.toList());

            // activityList 中嵌套放入 sortedTimeList
            mapByActivity.put("activityList", sortedTimeList);
            activityList.add(mapByActivity);
        });
        return activityList;
    }

//	@SuppressWarnings(value = { "rawtypes", "unused", "unchecked" })
//	@Override
//	public ResponseForm channelInfoStatistics(RequestForm param) {
//		ResponseForm result = new ResponseForm();
//		if (param.getData() != null) {
//			Map paramMap = (Map) param.getData();
//			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
//			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
//			// Date startTime = DateUtil.toDate(paramMap.get("startTime"));
//			// Date endTime = DateUtil.toDate(paramMap.get("endTime"));
//			// String channel = (String) paramMap.get("channel");
//			Map resultMap = new HashMap<>();
//			try {
//				/* 人数 */
//				List<Map> userList = wuMapper.quantityStatistics(paramMap);
//				/* 订单明细 */
//				List<Map> orderDetails = orderMapper.orderDetailStatistics(paramMap);
//				/* 百分比 */
//				BigDecimal percentum = new BigDecimal(0.15 + "");
//				/* 提成 */
//				BigDecimal profit = new BigDecimal(0);// 提成
//				BigDecimal totalFeeCount = new BigDecimal(0);// 总销售额
//				BigDecimal postageCount = new BigDecimal(0);// 运费
//				for (Map order : orderDetails) {
//					totalFeeCount = totalFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
//					postageCount = postageCount.add(new BigDecimal(order.get("postage").toString()));
//				}
//				totalFeeCount = totalFeeCount.subtract(postageCount);// 总价-运费
//				profit = totalFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);// 提成=总价*百分比
//				resultMap.put("quantity", Long.valueOf(userList.size()));
//				resultMap.put("orderQuantity", Long.valueOf(orderDetails.size()));
//				resultMap.put("profit", profit);
//				resultMap.put("totalFeeCount", totalFeeCount);
//				result.setStatus(true);
//				result.setCode("200");
//				result.setData(resultMap);
//			} catch (Exception e) {
//				e.printStackTrace();
//				result.setStatus(false);
//				result.setCode("400");
//				result.setMessage("请求错误");
//				log.error("请求错误");
//			}
//		} else {
//			result.setCode("400");
//			result.setStatus(false);
//			result.setMessage("参数不为空或缺少必要参数");
//		}
//		return result;
//	}

    @SuppressWarnings(value = {"rawtypes", "unused", "unchecked"})
    @Override
    public ResponseForm channelInfoStatistics(RequestForm param) {
        ResponseForm result = new ResponseForm();
        if (param.getData() != null) {
            Map paramMap = (Map) param.getData();
            paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
            paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
            String wxUid = (String) paramMap.get("wxUid");
            // Date startTime = DateUtil.toDate(paramMap.get("startTime"));
            // Date endTime = DateUtil.toDate(paramMap.get("endTime"));
            // String channel = (String) paramMap.get("channel");
            Map resultMap = new HashMap<>();
            try {
                /* 人数 */
                List<Map> userList = wuMapper.quantityStatistics(paramMap);
                /* 订单明细 */
                List<Map> orderDetails = orderMapper.orderDetailStatistics(paramMap);
                /* 百分比 */
                BigDecimal percentum = new BigDecimal(0.15 + "");
                /* 提成 */
                BigDecimal profit = new BigDecimal(0);// 提成
                BigDecimal totalFeeCount = new BigDecimal(0);// 总销售额
                BigDecimal postageCount = new BigDecimal(0);// 运费
                BigDecimal mineFeeCount = new BigDecimal(0);// 自己下单的总金额
                BigDecimal mineProfit = new BigDecimal(0);// 自己下单的提成=自己下单的总金额*百分比
                BigDecimal bFeeCount = new BigDecimal(0);// 子B下单的总金额
                BigDecimal bProfit = new BigDecimal(0);// 子B的提成=子B下单*百分比*百分比
                BigDecimal cFeeCount = new BigDecimal(0);// 子C下单的总金额
                BigDecimal cProfit = new BigDecimal(0);// 子C的提成=子C下单*百分比
                for (Map order : orderDetails) {
                    totalFeeCount = totalFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
                    totalFeeCount = totalFeeCount.subtract(new BigDecimal(order.get("postage").toString()));//总金额去运费
//					postageCount = postageCount.add(new BigDecimal(order.get("postage").toString()));
                    if (order.get("wxUid").toString().equals(wxUid) && order.get("isChannel").equals(1)) {
                        /* 自己 */
                        mineFeeCount = mineFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
                        mineFeeCount = mineFeeCount.subtract(new BigDecimal(order.get("postage").toString()));// 自己下单的总金额(去运费)
                    } else if (order.get("isChannel").equals(1)) {
                        /* 子B */
                        bFeeCount = bFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
                        bProfit = bProfit.subtract(new BigDecimal(order.get("postage").toString()));// 子B下单的总金额(去运费)
                    } else if (order.get("isChannel").equals(0)) {
                        /* 子C */
                        cFeeCount = cFeeCount.add(new BigDecimal(order.get("totalFee").toString()));
                        cProfit = cProfit.subtract(new BigDecimal(order.get("postage").toString()));// 子C下单的总金额(去运费)
                    }
                }
                mineProfit = mineFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);
                bProfit = (bFeeCount.multiply(percentum)).multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);
                cProfit = cFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);
                profit = profit.add(mineProfit).add(bProfit).add(cProfit);
//				totalFeeCount = totalFeeCount.subtract(postageCount);// 总价-运费
//				profit = totalFeeCount.multiply(percentum).setScale(2, BigDecimal.ROUND_HALF_UP);// 提成=总价*百分比
                resultMap.put("quantity", Long.valueOf(userList.size()));
                resultMap.put("orderQuantity", Long.valueOf(orderDetails.size()));
                resultMap.put("profit", profit);
                resultMap.put("totalFeeCount", totalFeeCount);
                result.setStatus(true);
                result.setCode("200");
                result.setData(resultMap);
            } catch (Exception e) {
                e.printStackTrace();
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("请求错误");
                log.error("请求错误");
            }
        } else {
            result.setCode("400");
            result.setStatus(false);
            result.setMessage("参数不为空或缺少必要参数");
        }
        return result;
    }

    @SuppressWarnings({"unused", "rawtypes", "unchecked"})
    @Override
    public ResponseForm channelUserDetails(RequestForm param) {
        ResponseForm result = new ResponseForm();
        if (param.getData() != null) {
            Map paramMap = (Map) param.getData();
            paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
            paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
            // Date startTime = DateUtil.toDate(paramMap.get("startTime"));
            // Date endTime = DateUtil.toDate(paramMap.get("endTime"));
            // String channel = (String) paramMap.get("channel");
            Map resultMap = new HashMap<>();
            try {
                /* 人数 */
                com.purchase.util.Page.parsePage(paramMap);
                Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
                List<Map> userList = wuMapper.quantityStatistics(paramMap);
                result.setCode("200");
                result.setStatus(true);
                result.setData(userList);
                result.setTotal((int) pageHelper.getTotal());
            } catch (Exception e) {
                e.printStackTrace();
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("请求错误");
                log.error("请求错误");
            }
        } else {
            result.setCode("400");
            result.setStatus(false);
            result.setMessage("参数不为空或缺少必要参数");
        }
        return result;
    }

    @Override
    public ResponseForm channelUserOrders(RequestForm param) {
        ResponseForm result = new ResponseForm();
        if (param.getData() != null) {
            Map paramMap = (Map) param.getData();
            paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
            paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
            // Date startTime = DateUtil.toDate(paramMap.get("startTime"));
            // Date endTime = DateUtil.toDate(paramMap.get("endTime"));
            // String channel = (String) paramMap.get("channel");
            Map resultMap = new HashMap<>();
            try {
                /* 订单明细 */
                com.purchase.util.Page.parsePage(paramMap);
                Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
                List<Map> orderDetails = orderMapper.orderDetailStatistics(paramMap);
                result.setCode("200");
                result.setStatus(true);
                result.setData(orderDetails);
                result.setTotal((int) pageHelper.getTotal());
            } catch (Exception e) {
                e.printStackTrace();
                result.setStatus(false);
                result.setCode("400");
                result.setMessage("请求错误");
                log.error("请求错误");
            }
        } else {
            result.setCode("400");
            result.setStatus(false);
            result.setMessage("参数不为空或缺少必要参数");
        }
        return result;
    }

    @Override
    public ResponseForm recommendMemberStatistics(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, String> paramMap = (Map<String, String>) param.getData();
        String wxUid = null;
        try {
            wxUid = paramMap.get("wxUid");
            if (!StringUtils.isNotBlank(wxUid)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }

            WxUserMember inviteWxUser = new WxUserMember();
            inviteWxUser.setWxUid(wxUid);
            inviteWxUser = wxUserMemberMapper.selectOne(inviteWxUser);

            //根据当前用户查询关联该用户推荐其他用户购买会员相关信息
            HashMap<String, Object> map = new HashMap<>();
            map.put("inviteWxUid", wxUid);
            List<Map<String, Object>> list = wxUserMemberMapper.recommendMemberStatistics(map);
            int recommendCount = list.size();
            int recommendCharge = 0;
            int withdrawCharge = 0;
            //如果当前用户是会员
            if (inviteWxUser.getRoleId() == 2) {
                recommendCharge = recommendCount * 20;
                withdrawCharge = recommendCount * 20;
            } else if (inviteWxUser.getRoleId() == 3) {
                recommendCharge = recommendCount * 28;
                withdrawCharge = recommendCount * 28;
            }
            //如果当前用户是代购
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("recommendCount", recommendCount);
            resultMap.put("recommendCharge", recommendCharge);
            resultMap.put("withdrawCharge", withdrawCharge);
            result.setData(resultMap);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("查询会员推广统计error" + wxUid, e);
        }
        return result;
    }

    @Override
    public ResponseForm cashBackStatistics(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, String> paramMap = (Map<String, String>) param.getData();
        String wxUid = null;
        try {
            wxUid = paramMap.get("wxUid");
            if (!StringUtils.isNotBlank(wxUid)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }

            //已返现金额
            BigDecimal haveBackCharge = BigDecimal.ZERO;
            //待返现金额
            BigDecimal waitBackCharge = BigDecimal.ZERO;
            //可提现金额
            BigDecimal withdrawableCharge = BigDecimal.ZERO;
            //已提现金额
            BigDecimal withdrawedCharge = BigDecimal.ZERO;
            //已返现订单
            int haveBackCount = 0;
            //待返现订单
            int waitBackCount = 0;

            Withdraw withdraw = new Withdraw();
            withdrawableCharge = withdraw.getWithdrawableCharge() == null ? BigDecimal.ZERO : withdraw.getWithdrawableCharge();
            withdrawedCharge = withdraw.getWithdrawedCharge() == null ? BigDecimal.ZERO : withdraw.getWithdrawedCharge();
            haveBackCharge = withdraw.getHaveBackCharge() == null ? BigDecimal.ZERO : withdraw.getHaveBackCharge();
            waitBackCharge = withdraw.getWaitBackCharge() == null ? BigDecimal.ZERO : withdraw.getWaitBackCharge();
            haveBackCount = withdraw.getHaveBackCount() == null ? 0 : withdraw.getHaveBackCount();
            waitBackCount = withdraw.getWaitBackCount() == null ? 0 : withdraw.getWaitBackCount();

            //统计待返现金额
            HashMap<String, Object> chargeMap = new HashMap<>();
            chargeMap.put("wxUid", wxUid);
            List<Map<String, Object>> waitBackCharges = withdrawMapper.getWaitBackCharges(chargeMap);
            for (Map<String, Object> charge : waitBackCharges) {
                waitBackCharge = new BigDecimal(String.valueOf(charge.get("charge"))).add(waitBackCharge);
            }

            //统计待返现订单
            waitBackCount = withdrawMapper.getWaitBackCount(chargeMap);

            //统计已返现金额，已返现订单
            Map<String, Object> haveBackInfo = withdrawMapper.getHaveBackInfo(wxUid);
            haveBackCharge = new BigDecimal(haveBackInfo.get("sum").toString());
            long count = (Long) haveBackInfo.get("count");
            haveBackCount = (int) count;

            //查询已提现金额
            withdrawedCharge = withdrawMapper.getWithdrawedCharge(wxUid);

            //统计可提现金额，可提现金额 = 已返现金额 - 已提现金额
            withdrawableCharge = haveBackCharge.subtract(withdrawedCharge);

            //todo 用户提现后修改提现表

            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("haveBackCount", haveBackCount);
            resultMap.put("haveBackCharge", haveBackCharge);
            resultMap.put("waitBackCount", waitBackCount);
            resultMap.put("waitBackCharge", waitBackCharge);
            resultMap.put("withdrawableCharge", withdrawableCharge);
            resultMap.put("withdrawedCharge", withdrawedCharge);
            result.setData(resultMap);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("查询代购返现统计error" + wxUid, e);
        }
        return result;
    }

    public static void main(String[] args) {
        Object a = 1;
        Object b = 0;
        System.out.println(b.equals(0));
    }
}
